package com.sy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sy.config.RedisClient;
import com.sy.constant.AppConstant;
import com.sy.dto.CartItem;
import com.sy.dto.Result;
import com.sy.entity.CollectionInfo;
import com.sy.entity.Product;
import com.sy.entity.User;
import com.sy.exception.ShopSystemException;

import com.sy.mapper.CartMapper;
import com.sy.mapper.CollectionMapper;
import com.sy.service.CartService;
import com.sy.service.GoodService;
import com.sy.service.UserService;
import com.sy.vo.CartProductParams;
import com.sy.vo.OrderItemParam;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description：
 * @Author: 孙玮立
 * @Date: 2020/3/11 16:23
 */

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private GoodService goodService;

    @Autowired
    private UserService userService;


    @Autowired
    private CartMapper cartMapper;


    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private RedisClient redisClient;

    /**
     * 当前用户添加购物车操作
     *
     * @param orderItemParam
     * @return
     */
    @Override
    public Result addToCart(String token, OrderItemParam orderItemParam) {
        Result result = new Result();
        try {
            User user =  userService.LoginUser(token);
            String count = String.valueOf(orderItemParam.getCount());
            Integer pid = orderItemParam.getPid();
            Product product =  goodService.getProductsByiId(pid);
            if (!count.matches(AppConstant.INTEGER_REGEX)) {
                throw new ShopSystemException("添加购物车的数量必须是一个整数");
            }
            String redisCartKey = AppConstant.USER_CART_REDIS_PREFIX + user.getId();
            String value = orderItemParam.getFlavor() +","+ orderItemParam.getPackaging() + ","+orderItemParam.getCount();
            redisClient.hset(redisCartKey, String.valueOf(pid), value);
            result.setCode(200);
            System.out.println(product);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 从redis中获取当前用户的购物车信息
     *
     * @return
     */
    @Override
    public Result getCartItems(String token) {
        Result result = new Result();
        try {
            User user = userService.LoginUser(token);
            String redisCartKey = AppConstant.USER_CART_REDIS_PREFIX + user.getId();
            System.out.println(redisCartKey);
            List<CartItem> cartItems = new ArrayList<>();
            Map<String, String> maps = redisClient.hgetAll(redisCartKey);
            if (MapUtils.isNotEmpty(maps)) {
                for (Map.Entry<String, String> map : maps.entrySet()) {
                    String pid = map.getKey();
                    String value = map.getValue();
                    List<String> list = Arrays.asList(value.split(","));
                    Product product = goodService.getProductsByiId(Integer.parseInt(pid));
                    CartItem cartItem = new CartItem();
                    cartItem.setProduct(product);
                    cartItem.setFlavor(list.get(0));
                    cartItem.setPackaging(list.get(1));
                    cartItem.setCount(Integer.valueOf(list.get(2)));
                    cartItems.add(cartItem);
                }
            }
            result.setData(cartItems);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 删除当前用户购物车中的产品信息
     * @param fields
     * @return
     */
    @Override
    public Result clearSomeCart(String token, String fields) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(fields)){
                throw new ShopSystemException("未选中任何产品");
            }
            User user = userService.LoginUser(token);
            String redisCartKey = AppConstant.USER_CART_REDIS_PREFIX + user.getId();
            redisClient.hDel(redisCartKey, fields);
            List<CartItem> cartItems = new ArrayList<>();
            Map<String, String> maps = redisClient.hgetAll(redisCartKey);
            if (MapUtils.isNotEmpty(maps)) {
                for (Map.Entry<String, String> map : maps.entrySet()) {
                    String pid = map.getKey();
                    String value = map.getValue();
                    List<String> list = Arrays.asList(value.split(","));
                    Product product = goodService.getProductsByiId(Integer.parseInt(pid));
                    CartItem cartItem = new CartItem();
                    cartItem.setProduct(product);
                    cartItem.setFlavor(list.get(0));
                    cartItem.setPackaging(list.get(1));
                    cartItem.setCount(Integer.valueOf(list.get(2)));
                    cartItems.add(cartItem);
                }
            }
            result.setData(cartItems);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;


    }

    /**
     * 更新购物车信息
     * @param token
     * @param pid
     * @param count
     * @return
     */
    @Override
    public Result updateCartItem(String token,String pid, String count) {
        Result result = new Result();
        try {
            User user = (User) userService.LoginUser(token);
            String redisCartKey = AppConstant.USER_CART_REDIS_PREFIX + user.getId();
            String hget = redisClient.hget(redisCartKey, pid);
            List<String> list = Arrays.asList(hget.split(","));
            list.set(2,count);
            redisClient.hset(redisCartKey,pid, StringUtils.join(list, ","));
            List<CartItem> cartItems = new ArrayList<>();
            Map<String, String> maps = redisClient.hgetAll(redisCartKey);
            if (MapUtils.isNotEmpty(maps)) {
                for (Map.Entry<String, String> map : maps.entrySet()) {
                    String value = map.getValue();
                    List<String> items = Arrays.asList(value.split(","));
                    Product product = goodService.getProductsByiId(Integer.parseInt(pid));
                    CartItem cartItem = new CartItem();
                    cartItem.setProduct(product);
                    cartItem.setFlavor(items.get(0));
                    cartItem.setPackaging(items.get(1));
                    cartItem.setCount(Integer.valueOf(items.get(2)));
                    cartItems.add(cartItem);
                }
            }
            result.setCode(200);
            result.setData(getCartItems(token).getData());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }

    /**
     * 添加收藏
     * @param token
     * @param pids
     * @return
     */
    @Override
    public Result addCollections(String token,String pids) {
        Result result = new Result();
        try {
            if (StringUtils.isBlank(pids)){
                throw new ShopSystemException("未选中任何产品");
            }
            User user = (User) userService.LoginUser(token);
            List<String> idsList = Arrays.asList(pids.split(","));
            for (String id:idsList){
                QueryWrapper<CollectionInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("pid",id).eq("uid",user.getId());
                CollectionInfo collection = collectionMapper.selectOne(queryWrapper);
                if (null != collection){
                    Product product = goodService.getProductsByiId(Integer.parseInt(id));
                    throw new ShopSystemException(product.getProductname() + "已经被收藏");
                }else {
                    CollectionInfo addcollection = new CollectionInfo();
                    addcollection.setPid(Integer.parseInt(id));
                    addcollection.setUid(user.getId());
                    collectionMapper.insert(addcollection);
                }
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setError(e.getMessage());
        }
        return result;
    }
}
